import store from '@/store'
// import Layout from '@/layout'
import { asyncRoutes } from '@/router'
import router from '@/router'
import { resetRouter } from '@/router'

export default async function refreshRoutes() {
  const routerType = store.getters.routerType
  const res = await store.dispatch('user/getUserInfo')
  // 筛选出来可以访问的路由
  // const filterRoutes = asyncRoutes
  store.commit('user/setRoutes', [])
  // 动态路由添加规则
  resetRouter()
  const filterRoutes = []
  asyncRoutes.forEach(item => {
    if (res.menuList.some(it => {
      // return (it.url === item.name && item.meta.routerType === routerType)
      return it.url === item.name
    })) {
      filterRoutes.push({
        path: item.path,
        component: item.component,
        redirect: item.redirect,
        hidden: !(item.meta.routerType === routerType),
        name: item.name,
        meta: item.meta,
        children: [...item.children]
      })
    }
  })
  // 筛选子路由不带排序
  filterRoutes.forEach(item => {
    item.children = item.children.filter(child => {
      return res.menuList.some(it => {
        return it.url === child.name
      })
    })
  })
  // filterRoutes.unshift({
  //   path: '/dashboard',
  //   component: Layout,
  //   redirect: '/dashboard',
  //   children: [{
  //     path: 'dashboard',
  //     name: 'Dashboard',
  //     component: () => import('@/views/dashboard/index'),
  //     meta: { title: '首页', icon: 'zhuye' }
  //   }]
  // })
  // 筛选子路由
  // filterRoutes.forEach(item => {
  //   item.children = item.children.map(child => {
  //     let asyncRoute = {}
  //     if (res.menuList.some(it => {
  //       if (it.url === child.name) {
  //         asyncRoute = it
  //         return true
  //       } else return false
  //     })) {
  //       return {
  //         ...child,
  //         meta: {
  //           ...child.meta,
  //           sort: asyncRoute.sort
  //         }
  //       }
  //     }
  //   })
  // })
  // 调用修改用户可以访问路由规则的mutation
  // filterRoutes.forEach(item => {
  //   item.children.sort((a, b) => {
  //     return a.meta.sort - b.meta.sort
  //   })
  // })
  // 调用修改用户可以访问路由规则的mutation
  store.commit('user/setRoutes', filterRoutes)
  router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
}
